/**
*收益牛人列表
*/
<template>
  <div>
    <gj-loadmore :bottom-method="loadBottom" :bottomPullText="bottomPullText" ref="loadmore">
      <div class="wrapper-xs bg-white"></div>
      <div class="cattle-person-table" v-for="(item,index) in dataList"  style="padding:0;overflow:hidden;"
           @click="clickBox(item)">
        <div class="hbox cattle-person-table-box gross-income-box" style="margin-top:0;">
          <div class="col head-icon v-middle skip">
            <img v-bind:src="item.headImgUrl" alt="">
          </div>
          <div class="col v-middle skip">
            <div class="color-56">{{item.nickname}}</div>
            <div class="color-9 text-xs">最大回撤<span class="color-blue m-l-xs">{{isEmpty(item.withdraw) ? '-' : item.withdraw.toFixed(2)}}</span>
            </div>
          </div>
          <div class="col v-middle text-center skip">
            <div class="cattle-person-table-rate">
              <div class="m-t-sm">总收益率</div>

              <div class="text-lg color-green" v-if="Number(item.total_rate)<0">{{item.total_rate.toFixed(2)}}%</div>

              <div class="text-lg color-red" v-else>{{item.total_rate.toFixed(2)}}%</div>

            </div>
          </div>
          <div class="col v-middle text-center col-x-1 has-btn" @click.stop="collapse(index,item)">
            <div class="cattle-person-circle-arrow-btn"
                 :class="{'cattle-person-circle-arrow-btn-transform':index===expandedIndex}"
                 data="id_<%=obj.client_id%>">
              <i class="iconfont icon-xiangxia"></i>
            </div>
          </div>
        </div>
        <div :style="{'height':expandedIndex===index?'77px':0}" :class="{'none-fake':expandedIndex!==index}"
             class="cattle-person-table-hbox-child-ref gross-income-box-ref hide-content-show">
          <div class="hbox cattle-person-table-hbox-child text-center">
            <div class="col v-middle">
              <div class="color-9">胜率</div>
              <div class="color-56 text-lg">{{isEmpty(item.victories) ? '-' : item.victories.toFixed(2)}}%</div>
            </div>
            <div class="col v-middle">
              <div class="color-9">近一月操作</div>
              <div class="color-56 text-lg">{{isEmpty(item.lastmothoptimes) ? '-' : item.lastmothoptimes}}次</div>
            </div>
            <div class="col v-middle text-center gross-income-oper" @click.stop="subscribe(item)" >
              <div class="cattle-person-circle-btn" v-show="item.subscribed!==''">
                <i class="iconfont " :class="{'icon-x':item.subscribed,'icon-dingyue':!item.subscribed}"></i>
              </div>
              <div><span class="color-9 text-xs" v-text="item.subscribed?'取消订阅':'订阅'"></span></div>
            </div>
          </div>
        </div>
      </div>
    </gj-loadmore>
    <subscribe-cancel-modal></subscribe-cancel-modal>
    <subscribe-modal></subscribe-modal>
  </div>
</template>

<script>
  import RemoteDAO from 'common/remoteDAO'
  import LocalDAO from 'common/localDAO'
  import CommonUtil from 'common/common.util'
  import LoadMore from 'components/LoadMore'
  import SubscribeCancelModal from 'components/modal/SubscribeCancelModal'
  import SubscribeModal from 'components/modal/SubscribeModal'

  export default {
    components: {
      'gj-loadmore': LoadMore,
      'subscribe-cancel-modal': SubscribeCancelModal,
      'subscribe-modal': SubscribeModal,
    },
    data(){
      return {
        userCode: '',
        nickName: '',
        pageInfo: {
          pageNum: 0,
          pageSize: 10,
        },
        count: 0,
        defUserHead: '',
        expandedIndex: '',
        transitionEndIndex: '',
        dataList: [],
        noData: false,
        subsChecked: {},
        bottomPullText: "向上滑动更多牛人"
      }
    },
    methods: {
      getPageParam(){
        return {
          start: this.pageInfo.pageNum * this.pageInfo.pageSize,
          end: (this.pageInfo.pageNum + 1) * this.pageInfo.pageSize
        }
      },
      subscribeCancelModal(relationUserCode, callback) {
        //订阅需传递要订阅的用户的userCode 即relationUserCode   callback:回调函数，若Number(response.error) === 0,则操作成功
        this.$store.dispatch('setModal', {
          visible: true,
          modalId: 'subscribeCancelModal',
          relationUserCode: relationUserCode,
          callback
        });
      },
      subscribeModal(relationUserCode, callback) {
        //取消需传递订阅的用户的userCode 即relationUserCode;   callback:回调函数，若Number(response.error) === 0,则操作成功
        this.$store.dispatch('setModal', {
          visible: true,
          modalId: 'subscribeModal',
          relationUserCode: relationUserCode,
          callback
        });
      },
      isEmpty(data){
        return data == null || data == undefined;
      },
      loadBottom() {
        let vm = this;

        vm.fetchData(function (allLoaded,error) {
          if(error){
            vm.$refs.loadmore.onBottomError(error);//单次加载失败或者没有数据，error为报错信息，如果是没有数据，写暂无数据
          }else if (allLoaded) {
            vm.$refs.loadmore.onBottomAllLoaded();//全部数据加载完成
          } else {
            vm.$refs.loadmore.onBottomLoaded(); //单次加载成功
          }
        });
      },
      collapse(index, item){
        let vm = this;

        item.visible = true;
        vm.expandedIndex = index === vm.expandedIndex ? '' : index;

        let userCode = vm.dataList[index].client_id;
        if (vm.expandedIndex !== '' && (!vm.subsChecked[userCode])) {
          if(vm.nickName){
            vm.checkSubscription(userCode, item);
          } else {
            item.subscribed = false;
          }
        }
      },
      //点击整行
      clickBox(item){
        item.expandedIndex = '';
        let vm = this;
        vm.$router.push({path: '/otherdetail', query: {userCode: item.client_id}})

        let userCode = LocalDAO.getUserCode();
        let kv = {"usercode": userCode, "k2": ""};
        TDAPP.onEvent("15005", "", kv);
        TDAPP.send();
      },
      //获取列表数据
      fetchData(afterFetchData){
        let vm = this,
          allLoaded = false,
          error = '',
          pageParam = vm.getPageParam();

        RemoteDAO.callJCL30012("1", pageParam.start, pageParam.end, vm.userCode, function (response) {

          if (response.error == "0") {
            let result = decrypt.json2(response.data);
            let body = JSON.parse(result).body || {};

            body.data.forEach(function (item) {
              item.headImgUrl = "";
              item.subscribed = ""; //订阅按钮线隐藏
              item.visible = false;
            });
            vm.dataList = vm.dataList.concat(body.data || []);

            if(vm.dataList.length == 0){
              error = '暂无数据'
            }else if (body.data.length < vm.pageInfo.pageSize){
              allLoaded = true
            }

            if (!allLoaded) {
              vm.pageInfo.pageNum++;
            }
            vm.getHeadPortraits(body.data, pageParam.start, pageParam.end); //获取头像
          } else {
            error = response.data
          }

          afterFetchData(allLoaded, error);
        });
      },
      //查询是否订阅
      checkSubscription(relationUserCode, item){
        let vm = this;

        RemoteDAO.callUC12008309(vm.userCode, "1", "1", "3", "1", "1", "", relationUserCode, "0", function (resp) {
          //标识已经查询过
          vm.subsChecked[relationUserCode] = true;
          resp = resp || {};
          let data = resp.data || {};
          let body = data.body;
          //body 不为空且返回集合大于0 说明已经订阅过
          item.subscribed = !CommonUtil.isEmpty(body) && body.length > 0;
        });
      },
      //订阅
      subscribe(item){
        let vm = this;

        if (!LocalDAO.getNickname()) {
          let kv = {"usercode": "", "k2": ""};
          TDAPP.onEvent("2015", "", kv);
          TDAPP.send();
          //注册或登录
          RemoteDAO.callNativeLogin(function (response) {
            if (response.error == 0) {
              vm.$store.dispatch('setTip',{text: "已为您登录，请重新查看点击"});
              setTimeout(function () {
                window.location.reload(true);
              },1000)
            } else {
              vm.$store.dispatch('setTip',{text:response.data});
            }
          });
        } else {
          let relationUserCode = item.client_id;
          if (item.subscribed) {
            vm.subscribeCancelModal(relationUserCode, function (response) {
              if (Number(response.error) == 0) {
                item.subscribed = false
              }
            })
            //取消订阅弹窗
          } else {
            //订阅弹窗
            vm.subscribeModal(relationUserCode, function (response) {
              if (Number(response.error) == 0) {
                item.subscribed = true
              }
            })
          }
        }
      },
      //批量获取头像
      getHeadPortraits(dataList, start, end){
        let vm = this,
          userCodes;

        userCodes = dataList.map(function (item) {
          return item.client_id;
        }).join(',');

        if (userCodes) {
          RemoteDAO.callUC12008316(vm.userCode, userCodes, function (resp) {
            if (resp.error == "0") {
              let body = resp.data.body || [];
              for (let i = 0; i < body.length; i++) {
                let usercode = body[i].USER_CODE;
                let headImgUrl = body[i].USER_HEAD || CommonUtil.getDefaultUserHead(usercode);

                for (let j = start; j < end; j++) {
                  if (vm.dataList[j].client_id == usercode) {
                    vm.dataList[j].headImgUrl = headImgUrl;
                  }
                }
              }
            }
          });
        }
      }
    },
    created(){
      let vm = this;

      vm.userCode = LocalDAO.getUserCode();//用户ID
      vm.nickName = LocalDAO.getNickname();//用户名
    }
  }
</script>

<style scoped>
  .cattle-person-table-hbox-child-ref.gross-income-box-ref.hide-content-show {
    transition: all 0.5s;
  }
  div.cattle-person-table{
     box-shadow: 0px 5px 15px rgb(207, 245, 236);
     margin:15px;
  }
  div.cattle-person-table .cattle-person-table-hbox-child-ref.none-fake::before,
  div.cattle-person-table .cattle-person-table-hbox-child-ref.none-fake::after{
    content: none;
  }
</style>
